/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.hugo.senai.view;

import br.com.hugo.senai.dao.Hibernate;
import br.com.hugo.senai.entities.Questao;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Hugo
 */
public class CopiaQuestao extends javax.swing.JFrame {

    /**
     * Creates new form CopiaQuestao
     */
    Questao q = (Questao) Hibernate.get(Questao.class, Menu.idQuestaoParaCopia);

    public CopiaQuestao() {
        initComponents();
        this.setIconImage(new ImageIcon(getClass().getResource("/br/com/hugo/senai/images/1413783129_edit-copy-128.png")).getImage());

        if (q.getResposta().isEmpty()) {
            taQuestao.setText(q.getEnunciado() + "\n\n"
                    + "a)" + q.getAlternativas().get(0)
                    + "\nb)" + q.getAlternativas().get(1)
                    + "\nc)" + q.getAlternativas().get(2)
                    + "\nd)" + q.getAlternativas().get(3));
        } else {
            taQuestao.setText(q.getEnunciado() + "\n\n Resposta (cópia opcional):\n\n"
                    + q.getResposta());
        }

        if (q.getImagem() != null) {
            lFoto.setIcon(new ImageIcon(new ImageIcon(q.getImagem()).getImage().getScaledInstance(200, 300, Image.SCALE_DEFAULT)));
        }

    }

    private void copy() {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        String text = taQuestao.getSelectedText();
        StringSelection selection = new StringSelection(text);
        clipboard.setContents(selection, null);
    }

    private void copy2() {
        // Cria uma instância de Toolkit responsável por pegar o conteúdo que está  na área de transferência
        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

        try {
        //    if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                ///////////////PARTE DE PEGAR DA ÁREA DE TRANSFERÊNCIA//////////////////////////////////////////
//                String text = (String) t.getTransferData(DataFlavor.stringFlavor);
//                text = text.toUpperCase();
                /////////////////////////FIM DA PARTE DE PEGAR DA TRANSFERÊNCIA/////////////////////////////////

                StringSelection ss = new StringSelection(taQuestao.getText()); // pega o conteúdo e o coloca na área de transferência novamente
                 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null); //Aqui realmente vai para a área de transferência
                //  CopyToClipboard.setClipboard((Image) lFoto.getIcon());
               // Toolkit.getDefaultToolkit().getSystemClipboard().setContents((Transferable) (Image) lFoto.getIcon(), null);

//                Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//
//                ImageIcon icon = new ImageIcon("omt.png", "");
                //ClipboardImage clipboardImage = new ClipboardImage(icon.getImage());
//                clipboard.setContents(, clipboard);
                //   taQuestao.setText(text);
              // ImageIcon ii = new ImageIcon(caminho);

                /* -- transfer image into clipboard */
                  //Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, transferable);

            }
         catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void copyaa() {
//        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//        ImageTransferable selection = new ImageTransferable(image);
//        clipboard.setContents(selection, null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        menuSalva = new javax.swing.JFileChooser();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taQuestao = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        lFoto = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        menuSalva.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
        menuSalva.setCurrentDirectory(null);
        menuSalva.setDialogTitle("");
        menuSalva.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        menuSalva.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
        menuSalva.setForeground(java.awt.Color.orange);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cópia da questão");

        jLabel1.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel1.setText("QUESTÃO");

        taQuestao.setColumns(20);
        taQuestao.setRows(5);
        jScrollPane1.setViewportView(taQuestao);

        jButton1.setText("Copiar texto para a área de transferência");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        lFoto.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lFoto.setText("FOTO");

        jButton2.setText("Salvar imagem");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Copiar imagem para a área de transferência");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton3)
                            .addComponent(lFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2))))
                .addGap(30, 30, 30))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lFoto, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(24, 24, 24))
        );

        setSize(new java.awt.Dimension(643, 455));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        copy2();
    }//GEN-LAST:event_jButton1ActionPerformed
    File diretorio;
    String caminho;


    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        menuSalva.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (menuSalva.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {

            diretorio = menuSalva.getSelectedFile();

            // JOptionPane.showMessageDialog(null, diretorio.getName());
            try {
                // Files.write(diretorio.toPath(), q.getImagem());
                //BufferedImage bufferedImage = q.getImagem();
//                InputStream inStream = new ByteArrayInputStream(q.getImagem());
//                BufferedImage bufferedImage = ImageIO.read(inStream);
//                ImageIO.write(bufferedImage, "jpg", Files.newOutputStream(Paths.get(diretorio.getAbsolutePath() + "\\imagem.jpg")));
                //File.copy

                FileOutputStream fos = new FileOutputStream(diretorio.getAbsolutePath() + "\\image.jpg");

                try {
                    fos.write(q.getImagem());
                    caminho = diretorio.getAbsolutePath() + "\\image.jpg";
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage());
                } finally {
                    fos.close();
                }

            } catch (IOException e) {
                System.out.println("erro");
            }
        }


    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
             TransferableImage transferable = new TransferableImage(new ImageIcon(q.getImagem()).getImage());
                Toolkit.getDefaultToolkit().getSystemClipboard().setContents(transferable,null );
             
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CopiaQuestao.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CopiaQuestao.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CopiaQuestao.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CopiaQuestao.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CopiaQuestao().setVisible(true);
            }
        });
    }

    static class TransferableImage implements Transferable {

        /* -- image for transfer */
        private Image image;

        /* -- constructor */
        public TransferableImage(Image image) {
            this.image = image;
        }

        /* -- when is performed check for image type, returns image */
        @Override
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
            if (isDataFlavorSupported(flavor)) {
                return image;
            } else {
                throw new UnsupportedFlavorException(flavor);
            }
        }

        /* -- method for checking supported type */
        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return flavor == DataFlavor.imageFlavor;
        }

        /* -- get supported type */
        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.imageFlavor};
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lFoto;
    private javax.swing.JFileChooser menuSalva;
    private javax.swing.JTextArea taQuestao;
    // End of variables declaration//GEN-END:variables
}
